package com.admin.his.user.web;


import com.admin.his.common.dto.JsonResponse;
import com.admin.his.common.entity.UserEntity;
import com.admin.his.common.exception.ThisSystemException;
import com.admin.his.user.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RequestMapping("/his")
@RestController
public class UserHandler {
    @Autowired
    UserService service;

    @RequestMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
    }

    @PostMapping("/login")
    public JsonResponse login(String account, String password, HttpSession session,String verCode,HttpServletRequest request) throws Exception {
        if (!CaptchaUtil.ver(verCode, request)) {
            CaptchaUtil.clear(request);  // 清除session中的验证码
            throw new ThisSystemException("verCode was wrong", "验证码不正确");
        }
        UserEntity user=service.login(account,password);
        session.setAttribute(UserHandler.class.getName(), user);
        JsonResponse result=new JsonResponse();
        result.setCode("ok");
        result.setData(user);
        return result;
    }

    @GetMapping("/session")
    public UserEntity getUser(HttpSession session)throws Exception{
        //从session中获取
        UserEntity user = (UserEntity) session.getAttribute(UserHandler.class.getName());
        if(user==null) {
            throw new ThisSystemException("nosession", "请先登录");
        }
        return user;
    }
}
